<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus';

// 表单数据
const user = ref({
  username: '139952',
  password: '123456',
  confirmPassword: '123456'
});
const activeName = ref('login');
// 路由实例
const router = useRouter();
// 登录处理函数
const handleLogin = () => {
  // 直接跳转到管理页面（示例路径为'/admin'）
  // 表单验证通过后
  const loginData = { 
    "sid": user.value.username, 
    "password": user.value.password 
  };
  console.log('发送登录请求数据：', loginData);
  
  axios.post('http://localhost:3000/api/login', loginData).then(res => {
    console.log('登录响应数据：', res.data);
    if (res.data.code === 200) {
      ElMessage.success('登录成功');
      // 1秒后跳转
      setTimeout(() => {
        router.push('/admin');
      }, 1000);
    } else {
      ElMessage.error(`登录失败：${res.data.message || '用户名或密码错误'}`);
    }
  }).catch(err => {
    console.error('登录错误详情：', err.response?.data || err);
    ElMessage.error(`连接服务器失败: ${err.response?.data?.message || err.message}`);
  });
};

var validatePassword = (rule, value, callback) => {
  if (value !== user.value.password) {
    callback(new Error('两次密码不一致'));
  } else {
    callback();
  }
};

const rules = ref({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度为6-12位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请输入确认密码', trigger: 'blur' },
    { min: 6, max: 12, message: '密码长度为6-12位', trigger: 'blur' },
    { validator: validatePassword, trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择权限', trigger: 'blur' }
  ]
});

// 注册方法
const handleRegister = () => {
  // 验证用户是否存在
  const checkData = { "sid": user.value.username };
  console.log('发送用户检查请求数据：', checkData);
  
  axios.post('http://localhost:3000/api/check', checkData).then(res => {
    console.log('用户检查响应数据：', res.data);
    if (res.data.code === 200) {
      ElMessage.error('用户已存在');
    } else {
      const registerData = { 
        "sid": user.value.username, 
        "password": user.value.password, 
        "role": user.value.role 
      };
      console.log('发送注册请求数据：', registerData);
      
      axios.post('http://localhost:3000/api/register', registerData).then(res => {
        console.log('注册响应数据：', res.data);
        if (res.data.code === 200) {
          ElMessage.success('注册成功');
          setTimeout(() => {
            activeName.value = 'login';
          }, 3000);
        } else {
          ElMessage.error(`注册失败：${res.data.message || '未知错误'}`);
        }
      }).catch(err => {
        console.error('注册错误详情：', err.response?.data || err);
        ElMessage.error(`注册失败: ${err.response?.data?.message || err.message}`);
      });
    }
  }).catch(err => {
    console.error('用户检查错误详情：', err.response?.data || err);
    ElMessage.error(`用户检查失败: ${err.response?.data?.message || err.message}`);
  });
};
</script>

<template>
  <div class="login-container">
    <el-card>
      <!-- 登录和注册选项卡 -->
      <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
        <el-tab-pane label="登录" name="login">
          <el-card class="login-card">
            <h2 class="login-title">用户登录</h2>
            <el-form class="login-form" :model="user" :rules="rules">
              <el-form-item prop="username">
                <!-- 增加标题 -->
                <span>用户名</span>
                <el-input v-model="user.username" placeholder="请输入用户名" prefix-icon="el-icon-user" />
              </el-form-item>
              <el-form-item prop="password">
                <!-- 增加标题 -->
                <span>密码</span>

                <el-input v-model="user.password" placeholder="请输入密码" type="password" prefix-icon="el-icon-lock" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="login-btn" @click="handleLogin">登录</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
        <el-tab-pane label="注册" name="register">
          <el-card class="login-card">
            <h2 class="login-title">用户注册</h2>
            <el-form class="register-form" :model="user" :rules="rules">
              <el-form-item prop="username">
                <span>用户名</span>
                <el-input v-model="user.username" placeholder="请输入用户名" prefix-icon="el-icon-user" />
              </el-form-item>
              <el-form-item prop="password">
                <span>密码</span>
                <el-input v-model="user.password" placeholder="请输入密码" type="password" prefix-icon="el-icon-lock" />
              </el-form-item>
              <!-- 确认密码 -->
              <el-form-item prop="confirmPassword">
                <span>确认密码</span>
                <el-input v-model="user.confirmPassword" placeholder="请输入确认密码" type="password"
                  prefix-icon="el-icon-lock" />
              </el-form-item>
              <!-- 权限 -->
              <el-form-item prop="role">
                <span>权限</span>
                <el-select v-model="user.role" placeholder="请选择权限">
                  <el-option label="学生" value="1" />
                  <el-option label="教师" value="2" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" class="login-btn" @click="handleRegister">注册</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>

</template>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f0f2f5;
}

.login-card {
  width: 550px;
  padding: 30px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  margin-bottom: 30px;
  font-size: 24px;
  color: #333;
}

.login-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

.login-btn {
  width: 100%;
  height: 40px;
  font-size: 16px;
}
</style>
